﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Innova.Microfinanzas.Business.UsersAndSecurity;
using Innova.Microfinanzas.BusinessEntities;
using MyCommerce.ManagementBase.Common.Base.Common;

namespace MyCommerce.Common.CommerceClient.Security
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        public LoginForm(User objUserLoad)
        {
            InitializeComponent();
            if (objUserLoad != null)
            {
                btnCloseAll.Visible = true;
                btnCancel.Visible = false;
                fieldUserName.Text = objUserLoad.UserName;
                fieldUserName.ReadOnly = true;
                fieldUserName.TabStop = false;
            }
        }

        public event EventHandler OnCloseAll;

        public User ObjUserLoged
        {
            get;
            set;
        }

        public List<Command> ColCommandsAvailable
        {
            get;
            set;
        }

        #region Login Methods

        private void DoLogin()
        {
            LoginWithCredentials();
        }

        private void LoginWithCredentials()
        {
            try
            {
                if (ValidateCredentials())
                {                    
                    UserManager userMgr = new UserManager();
                    User objUserLoged = userMgr.AuthenticatedUser(fieldUserName.Text.Trim(), fieldPassword.Text);
                    if (objUserLoged != null)
                    {
                        if (objUserLoged.GeneratedPassword)
                        {
                            List<string> colData = new List<string>();
                            while (colData != null
                                && colData.Count <= 1)
                            {
                                colData = LiteUserChangePassword.ChangePassword(fieldPassword.Text);
                                if (colData == null
                                    || colData.Count <= 1)
                                    MessageBox.Show("Debe cambiar la contraseña del usuario para poder ingresar al sistema.", "Usuarios", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            userMgr.ChangeUserPassword(objUserLoged.IdUser, colData);
                            MessageBox.Show("La contraseña fue cambiada correctamente.", "Usuarios", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        ObjUserLoged = objUserLoged;
                        ColCommandsAvailable = userMgr.GetUserCommands(fieldUserName.Text.Trim());
                        DialogResult = System.Windows.Forms.DialogResult.OK;
                        Close();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error al autenticar", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private bool ValidateCredentials()
        {
            StringBuilder message = new StringBuilder();
            bool vResult = true;
            if (String.IsNullOrEmpty(fieldUserName.Text.Trim()))
            {
                vResult = false;
                message.AppendLine("Debe ingresar un nombre de usuario.");
            }
            if (String.IsNullOrEmpty(fieldPassword.Text.Trim()))
            {
                vResult = false;
                message.AppendLine("Debe ingresar una contraseña.");
            }
            if(!vResult)
                MessageBox.Show(message.ToString(), "Login", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return vResult;
        }

        #endregion

        private void btnLogin_Click(object sender, EventArgs e)
        {
            DoLogin();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
            Close();
        }

        private void fieldUserName_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                fieldPassword.Focus();
            }
        }

        private void fieldPassword_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnLogin.Focus();
                btnLogin_Click(this, new EventArgs());
            }
        }

        private void btnCloseAll_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
            if (OnCloseAll != null)
                OnCloseAll(this, new EventArgs());
        }
    }
}
